<?php
declare (strict_types=1);

namespace app\command\Test;

use app\constant\CommonConstant;
use app\constant\ModelConstant;
use app\event\FacebookPixelTrackEvent;
use app\event\PushOrderToShopify;
use app\helpers\UtilHelper;
use app\libs\SpreedlySDK\Action\GatewaysAPI;
use app\libs\SpreedlySDK\Action\PaymentMethodAPI;
use app\libs\SpreedlySDK\Action\PurchaseAPI;
use app\model\BatchUpdate;
use app\model\FacebookPixels;
use app\model\LineItems;
use app\model\Notify;
use app\model\Orders;
use app\model\PixelLogs;
use app\model\ShopsPayment;
use app\queue\TestQueue;
use app\service\pixel\FaceBookPixelTrack;
use app\service\shopify\action\graph\OrderGraph;
use app\service\shopify\action\graph\ProductGraph;
use app\trait\OrderTrait;
use app\trait\PaymentTrait;
use app\trait\ShopifyTrait;
use Carbon\Carbon;
use Omnipay\Omnipay;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use think\facade\Event;
use think\facade\Queue;
use think\helper\Arr;

class LfxTest extends Command
{
    use PaymentTrait, OrderTrait, ShopifyTrait;

    protected $clientId = 'AStgX20Bx4ZGVF7OovRksHtjOvCXxOz4F0KsE35TRu_v-JbMSO61cTfpAnFfQ9G5KhOA4CwiOgRzoYaW';
    protected $secret = 'EPivtk3r7bBXQIJlkFEctTb_poZXZnNvkQ_Me87I185b9xHtdADMlPgy30sWicsD2kZXmNTlXc5MoWHM';

    protected function configure()
    {
        // 指令配置
        $this->setName('lfx:test')
            ->setDescription('the lfxtest command');
    }

    protected function execute(Input $input, Output $output)
    {
        $order = Orders::find(71);
        Event::trigger("FacebookPixelTrackEvent",new FacebookPixelTrackEvent($order));

        dd(11);



        //https://spftest.adspromobi.com/api/v1/checkout/39?=&loading_path=&return_path=&success=false
        $arr = [
            "https://quickstart-fec6fc7d_myshopify_com/",
            "loading_path"=>"a/s/hWN2HSmR8boJByBOM8BLo9Mi/credit-card-3ds-redirect-loading",
            "return_path"=>"/products/waterproof-durable-easy-colored-machete-eyebrow-pencil?variant=47762515001596"
        ];
        //dd(UtilHelper::buildQueryString($arr));

        $api = new GatewaysAPI();
//        $body = [
//            'gateway'=>[
//                'gateway_type'=>'test',
//                "description"=>"test",
//                "sandbox"=>true
//            ],
//        ];
//        $res = $gateway->create_gateways($body);
//        dd($res);
        //$res = $api->check_env("44334FZM998SNV5PP1VNKCHZ93");
        //dd($res);
        // 创建payment_method
        $api = new PaymentMethodAPI();
        $payment_data = [
            'protocolVersion' => "ECv1",
            "signature" => "MEYCIQDtiQjAad89WXC4aC0G4FY9EjR1A3ogULBvDryJFjMESQIhAPqLxJD6LZAZwZlwG4w/wx144X5P0me+28J+N11+cHPR",
            "signedMessage" => "{\"encryptedMessage\":\"AbVwM4VvnCfZxVNqmB4yxx3ZV7632inewDrpAGa+UmI9Jcted+LDZNpMI4ydLlDHqmiuzYhxkns9EsfHhz0EgFZnjpRA71JlPegMM0Xn1ARIlvoGMGajD1qDuA7jka0dA/N13dTmt/4PieIh+ny6TZ33jtoTjNdLdeZ+/symQkXHtwLcsWkntpTnP+3EL8ZVDFaN0YxQdRU9q+JVrcDw4OOO0lJqyl4FZpMiXvSk2hzw9evnwXMEvco1cwFxIp9f3SmQQ1suoLDeNQKDgQ+ofSwphyDi8nh+4G7vMeowHDG6i5L1gsrL+GxLRiaugY6TuNkjwzog0Zx7XjHUC8RR03Ua5lyvTF1yIa7RU3CVEECEks7AJuKjpJvRT3lhAEG3ek+qTKZkKEZ52qmpzP8SZGARNy/K/diAIm7ZhK1ETWaMyldHsVYSRwFaMdasaznu\",\"ephemeralPublicKey\":\"BJQy2NZ+XpN5TJs8CJFr0oebfaQBT7tXXXquGzzpUrSyBvKLmEJJX5GjyBQHTW0j6g5w1FB1GHvL/9bkoBtrhYM\\u003d\",\"tag\":\"DWOj76eR5beBSyl4Fm+8yq+yiW/YdByd/2CH+UBQrt8\\u003d\"}",
        ];

        $google_pay = [
            'payment_method' => [
                'google_pay' => [
                    "payment_data" => $payment_data,
//                    "first_name"=>"l",
//                    "last_name"=>"fx",
//                    "address1"=> "1410 15th Street",
//                    "city"=> "San Francisco",
//                    "country"=> "US",
                ],
//                "email"=>"291203947@qq.com",
//                'state'=>'CA',
//                'zip'=>"94103",
//                "retained"=>true
            ]
        ];
        $credit_card = [
            'payment_method' => [
                'credit_card' => [
                    "first_name" => "John",
                    "last_name" => "Doe",
                    'number' => "4111111111111111",
                    "month" => "12",
                    "year" => "2030",
                    "verification_value" => "123"
                ]
            ]
        ];
        //$res = $api->create_payment_method($google_pay);
        //dd($res);
        $api = new PurchaseAPI();
        $token = '4VFW78S6C084592QY2H4N4H916';
        $body = [
            "transaction" => [
                "amount" => "100",
                "currency_code" => "USD",
                "description" => "test",
                "email" => "291203947@qq.com",
//                "google_pay" => [
//                    "payment_data" => $payment_data,
//                    "test_card_number"=>"4111111111111111"
//                ],

                "credit_card" => [
                    "first_name" => "John",
                    "last_name" => "Doe",
                    'number' => "4111111111111111",
                    "month" => "12",
                    "year" => "2030",
                    "verification_value" => "123"
                ]
            ],

        ];

        dump($body);
        $res = $api->purchase($token, $body);
        dd($res);

    }


    public function completedSp($data)
    {
        $order = Orders::find($data);
        try {
            if (is_null($order)) throw new \Exception("订单不存在");
            dump('***********正在执行订单ID: ' . $data . '**********');
            if ($order->order_status != Orders::ORDER_STATUS_COMPLETED) throw new \Exception('订单未支付');
            $firstPurchase = $order->purchases()
                ->where('order_status', Orders::ORDER_STATUS_COMPLETED)
                ->findOrEmpty();
            $tags = [$order->trade_no, $order->pay_method_name];
            $updateDraft = [];
            if (!$firstPurchase->isEmpty()) {
                $lineItems = LineItems::query()
                    ->whereIn('order_id', [$order->id, $firstPurchase->id])
                    ->field(['price', 'variant_id as id', 'quantity', 'sku'])
                    ->select()
                    ->toArray();
                $lineItems = $this->formatDraftItems($lineItems, $order->present_currency);
                $updateDraft['lineItems'] = $lineItems;
                $tags = [$order->trade_no, $firstPurchase->trade_no, $order->pay_method_name];
            }
            $updateDraft['tags'] = $tags;
            if ($order->is_paypal_kj) {
                $updateDraft['email'] = $order->email;
                $updateDraft['shippingAddress'] = [
                    "address1" => $order->shippingAddress->address1,
                    "city" => $order->shippingAddress->city,
                    "province" => $order->shippingAddress->province,
                    "country" => $order->shippingAddress->country,
                    "zip" => $order->shippingAddress->zip
                ];
            }
            dump("更新订单ID: {$data}", $updateDraft);
            $draftApi = new OrderGraph($order->shop_id, true);
            $result = $draftApi->update_draft_order($order->draft_id, $updateDraft);//更新订单
            dump("更新订单结果: {$data}", $result);
            $completeResult = $draftApi->complete_draft_order($order->draft_id);//保存结果
            dump("完成订单ID结果: {$data}", $completeResult);
            $this->saveDraftResult($order, $completeResult, 'draftOrderComplete');
            Notify::saveParams($order->id, ['update_draft_params' => $updateDraft, 'update_response' => $result, 'complete_response' => $completeResult], Notify::TYPE_COMPLETE_DRAFT, $order->pay_method);//创建草稿订单

        } catch (\Exception $e) {
            dump($e);
            if ($order) Orders::saveExceptionMessage($order, $e->getMessage());
        }
    }


    public function paypalOmnipay()
    {
        $paypal = Omnipay::create('PayPal_Rest');
        $paypal->initialize(
            [
                'clientId' => 'AStgX20Bx4ZGVF7OovRksHtjOvCXxOz4F0KsE35TRu_v-JbMSO61cTfpAnFfQ9G5KhOA4CwiOgRzoYaW',
                'secret' => 'EPivtk3r7bBXQIJlkFEctTb_poZXZnNvkQ_Me87I185b9xHtdADMlPgy30sWicsD2kZXmNTlXc5MoWHM',
                'testMode' => true
            ]
        );
        $url = 'https://www.baidu.com';
        $amount = '1.00';
        $currency = 'USD';
        $params = [
            'intent' => 'sale',
            'payer' => ['payment_method' => 'paypal'],
            'transactions' => [
                [
                    'amount' => [
                        'total' => $amount,
                        'currency' => $currency,
                    ],
                    'item_list' => [
                        'items' => [
                            [
                                "name" => "hat",
                                "description" => "Brown hat.",
                                "quantity" => 1,
                                "price" => $amount,
                                "sku" => 'SKU0055',
                                "currency" => $currency
                            ]
                        ],
                    ],
                    'notify_url' => $url
                ]
            ],
            'redirect_urls' => [
                'return_url' => $url,
                'cancel_url' => $url
            ],
        ];
        $response = $paypal->purchase()->sendData($params);
        dd($response->getData());
    }
}
